

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>Twitter Geolocation Predictor &mdash; Twitter Geolocation Predictor 0.1 documentation</title>
  

  
  
  
  

  

  
  
    

  

  
  
    <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  

  

  
        <link rel="index" title="Index"
              href="genindex.html"/>
        <link rel="search" title="Search" href="search.html"/>
    <link rel="top" title="Twitter Geolocation Predictor 0.1 documentation" href="#"/>
        <link rel="next" title="Data" href="source/twgeo.data.html"/>
    <link href="_static/mystyles.css" rel="stylesheet" type="text/css">


  
  <script src="_static/js/modernizr.min.js"></script>

</head>

<body class="wy-body-for-nav" role="document">

   
  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side">
      <div class="wy-side-scroll">
        <div class="wy-side-nav-search">
          

          
            <a href="#" class="icon icon-home"> Twitter Geolocation Predictor
          

          
          </a>

          
            
            
              <div class="version">
                0.1
              </div>
            
          

          
<div role="search">
  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

          
        </div>

        <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          
            
            
              
            
            
              <p class="caption"><span class="caption-text">API</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="source/twgeo.data.html">Data</a></li>
<li class="toctree-l1"><a class="reference internal" href="source/twgeo.models.html">Models</a></li>
</ul>

            
          
        </div>
      </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        
          <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
          <a href="#">Twitter Geolocation Predictor</a>
        
      </nav>


      
      <div class="wy-nav-content">
        <div class="rst-content">
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="wy-breadcrumbs">
    
      <li><a href="#">Docs</a> &raquo;</li>
        
      <li>Twitter Geolocation Predictor</li>
    
    
      <li class="wy-breadcrumbs-aside">
        
            
            <a href="_sources/index.rst.txt" rel="nofollow"> View page source</a>
          
        
      </li>
    
  </ul>

  
  <hr/>
</div>
          <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
           <div itemprop="articleBody">
            
  <div class="section" id="twitter-geolocation-predictor">
<h1>Twitter Geolocation Predictor<a class="headerlink" href="#twitter-geolocation-predictor" title="Permalink to this headline">¶</a></h1>
<p>This is a deep-learning tool to predict the location of a Twitter user
based solely on the text content of his/her tweets without any other
form of metadata.</p>
<div class="section" id="overview">
<h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2>
<p>The Twitter Geolocation Predictor is a Recurrent Neural Network
classifier. Every training sample is a collection of tweets labeled with
a location (e.g. country, state, city, etc.). The model will
tokenize all tweets into a sequence of words, and feed them into an
<a class="reference external" href="https://en.wikipedia.org/wiki/Word_embedding">Embedding Layer</a>. The
embeddings will learn the meaning of words and use them as input for two
stacked <a class="reference external" href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">Long-Short Term
Memory</a>
layers. A <a class="reference external" href="https://en.wikipedia.org/wiki/Softmax_function">Softmax</a>
fully-connected layer at the end yields the classification result.</p>
<a class="reference internal image-reference" href="https://dl.dropbox.com/s/tvar2ccihtq0ijg/GeoModelGraph.png"><img alt="https://dl.dropbox.com/s/tvar2ccihtq0ijg/GeoModelGraph.png" class="align-center" src="https://dl.dropbox.com/s/tvar2ccihtq0ijg/GeoModelGraph.png" style="width: 500px;" /></a>
</div>
<div class="section" id="getting-started">
<h2>Getting Started<a class="headerlink" href="#getting-started" title="Permalink to this headline">¶</a></h2>
<div class="section" id="dependencies">
<h3>Dependencies<a class="headerlink" href="#dependencies" title="Permalink to this headline">¶</a></h3>
<ol class="arabic simple">
<li>Python 3.5</li>
<li>tensorflow</li>
<li>keras</li>
<li>nltk</li>
<li>pandas</li>
<li>numpy</li>
<li>sqlalchemy</li>
<li>sklearn</li>
<li>psycopg2</li>
</ol>
</div>
<div class="section" id="installation">
<h3>Installation<a class="headerlink" href="#installation" title="Permalink to this headline">¶</a></h3>
<p>Clone the repository and install all the dependencies using pip.</p>
<div class="code console highlight-default"><div class="highlight"><pre><span></span>$ git clone git@github.com:jmatias/uiuc-twitter-geolocation.git
$ cd uiuc-twitter-geolocation
$ sudo pip3 install -r requirements.txt
</pre></div>
</div>
<p>This will install the latest CPU version of Tensorflow. If you would
like to run on a GPU, follow the Tensorflow-GPU <a class="reference external" href="https://www.tensorflow.org/install/">installation
instructions</a>.</p>
</div>
<div class="section" id="using-a-pre-processed-dataset">
<h3>Using A Pre-Processed Dataset<a class="headerlink" href="#using-a-pre-processed-dataset" title="Permalink to this headline">¶</a></h3>
<p>The tool comes with a built-in dataset of ~430K users located in the
U.S. (~410K for training, ~10K for development and ~10K for testing). To
train a model using this dataset, run the train.py sample script.</p>
<p>Note: The dataset has a size of approximately 2.5GB.</p>
<div class="highlight-console"><div class="highlight"><pre><span></span><span class="gp">$</span> python3 train.py --epochs <span class="m">5</span> --batch_size <span class="m">32</span> --vocab_size <span class="m">20000</span> --hidden_size <span class="m">100</span> --max_words <span class="m">100</span> --classifier state

<span class="go">Using TensorFlow backend.</span>
<span class="go">Downloading data from https://dl.dropbox.com/s/ze4ov5j30u9rf5m/twus_test.pickle</span>
<span class="go">55181312/55180071 [==============================] - 11s 0us/step</span>
<span class="go">Downloading data from https://dl.dropbox.com/s/kg09i1z32n12o98/twus_dev.pickle</span>
<span class="go">57229312/57227360 [==============================] - 12s 0us/step</span>
<span class="go">Downloading data from https://dl.dropbox.com/s/0d4l6jmgguzonou/twus_train.pickle</span>
<span class="go">2427592704/2427591168 [==============================] - 486s 0us/step</span>

<span class="go">Building model...</span>
<span class="go">Hidden layer size: 100</span>
<span class="go">Analyzing up to 100 words for each sample.</span>
<span class="go">Building tweet Tokenizer using a 20,000 word vocabulary. This may take a while...</span>
<span class="go">Tokenizing tweets from 59,546 users. This may take a while...</span>
<span class="go">Training model...</span>
<span class="go">Train on 50000 samples, validate on 9546 samples</span>
<span class="go">Epoch 1/1</span>
<span class="go">    1664/50000 [..............................] - ETA: 3:59 - loss: 3.8578 - acc: 0.0950 - top_5_acc: 0.2536</span>
</pre></div>
</div>
<p>You can also try using this data from your own source code.</p>
<div class="highlight-ipython"><div class="highlight"><pre><span></span><span class="n">In</span> <span class="p">[</span><span class="mi">1</span><span class="p">]:</span> <span class="kn">from</span> <span class="nn">twgeo.data</span> <span class="kn">import</span> <span class="n">twus_dataset</span>
<span class="n">Using</span> <span class="n">TensorFlow</span> <span class="n">backend</span><span class="o">.</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">2</span><span class="p">]:</span> <span class="n">x_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">x_dev</span><span class="p">,</span> <span class="n">y_dev</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">twus_dataset</span><span class="o">.</span><span class="n">load_state_data</span><span class="p">()</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="n">x_train</span><span class="o">.</span><span class="n">shape</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="p">(</span><span class="mi">410336</span><span class="p">,)</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="n">y_train</span><span class="o">.</span><span class="n">shape</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="p">(</span><span class="mi">410336</span><span class="p">,)</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">5</span><span class="p">]:</span> <span class="n">x_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">x_dev</span><span class="p">,</span> <span class="n">y_dev</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">twus_dataset</span><span class="o">.</span><span class="n">load_state_data</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="s1">&#39;small&#39;</span><span class="p">)</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="n">x_train</span><span class="o">.</span><span class="n">shape</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="p">(</span><span class="mi">50000</span><span class="p">,)</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">7</span><span class="p">]:</span> <span class="n">y_train</span><span class="o">.</span><span class="n">shape</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">7</span><span class="p">]:</span> <span class="p">(</span><span class="mi">50000</span><span class="p">,)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="pre-processing-your-own-data">
<h2>Pre-Processing your own data<a class="headerlink" href="#pre-processing-your-own-data" title="Permalink to this headline">¶</a></h2>
<table border="1" class="docutils">
<colgroup>
<col width="85%" />
<col width="15%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Tweet Text</th>
<th class="head">Location</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Hello world! This is a tweet. &lt;eot&gt; This is another tweet. &lt;eot&gt;</td>
<td>Florida</td>
</tr>
<tr class="row-odd"><td>Going to see Star Wars tonite!</td>
<td>Puerto Rico</td>
</tr>
<tr class="row-even"><td>Pizza was delicious! &lt;eot&gt; I’m another tweeeeeet &lt;eot&gt;</td>
<td>California</td>
</tr>
</tbody>
</table>
<p>Given a raw dataset stored in a CSV file like the one shown above, we can preprocess said data using <code class="code docutils literal"><span class="pre">twgeo.data.input.read_csv_data()</span></code>. This function will:</p>
<blockquote>
<div><ol class="arabic simple">
<li>Tokenize the tweet text.</li>
<li>Limit repeated characters to a maximum of 2. For example: ‘Greeeeeetings’ becomes ‘Greetings’.</li>
<li>Perform <a class="reference external" href="https://en.wikipedia.org/wiki/Stemming">Porter stemming</a> on each token.</li>
<li>Convert each token to lower case.</li>
</ol>
</div></blockquote>
<p>The location data may be any string or integer value.</p>
<div class="code python highlight-default"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">twgeo.data.input</span> <span class="k">as</span> <span class="nn">input</span>
<span class="n">tweets</span><span class="p">,</span> <span class="n">locations</span> <span class="o">=</span> <span class="nb">input</span><span class="o">.</span><span class="n">read_csv_data</span><span class="p">(</span><span class="s1">&#39;mydata.csv&#39;</span><span class="p">,</span> <span class="n">tweet_txt_column_idx</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">location_column_idx</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="training-the-model">
<h2>Training the Model<a class="headerlink" href="#training-the-model" title="Permalink to this headline">¶</a></h2>
<div class="code python highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">twgeo.models.geomodel</span> <span class="k">import</span> <span class="n">Model</span>
<span class="kn">from</span> <span class="nn">twgeo.data</span> <span class="k">import</span> <span class="n">twus</span>

<span class="c1"># x_train is an array of text. Each element contains all the tweets for a given user.</span>
<span class="c1"># y_train is an array of integer values, corresponding to each particular location we want to train against.</span>
<span class="n">x_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">x_dev</span><span class="p">,</span> <span class="n">y_dev</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">twus</span><span class="o">.</span><span class="n">load_state_data</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="s1">&#39;small&#39;</span><span class="p">)</span>

<span class="c1"># num_outputs is the total number of possible classes (locations). In this example, 50 US states plus 3 territories.</span>
<span class="c1"># time_steps is the total number of individual words to consider for each user.</span>
<span class="c1"># Some users have more tweets then others. In this example, we are capping it at a total of 500 words per user.</span>
<span class="n">geoModel</span> <span class="o">=</span> <span class="n">Model</span><span class="p">(</span><span class="n">batch_size</span><span class="o">=</span><span class="mi">64</span><span class="p">)</span>
<span class="n">geoModel</span><span class="o">.</span><span class="n">build_model</span><span class="p">(</span><span class="n">num_outputs</span><span class="o">=</span><span class="mi">53</span><span class="p">,</span> <span class="n">time_steps</span><span class="o">=</span><span class="mi">500</span><span class="p">,</span><span class="n">vocab_size</span><span class="o">=</span><span class="mi">20000</span><span class="p">)</span>

<span class="n">geoModel</span><span class="o">.</span><span class="n">train</span><span class="p">(</span><span class="n">x_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">x_dev</span><span class="p">,</span> <span class="n">y_dev</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="n">geoModel</span><span class="o">.</span><span class="n">save_model</span><span class="p">(</span><span class="s1">&#39;mymodel&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="making-predictions">
<h2>Making Predictions<a class="headerlink" href="#making-predictions" title="Permalink to this headline">¶</a></h2>
<div class="code ipython highlight-default"><div class="highlight"><pre><span></span><span class="n">In</span> <span class="p">[</span><span class="mi">1</span><span class="p">]:</span> <span class="kn">from</span> <span class="nn">twgeo.models.geomodel</span> <span class="k">import</span> <span class="n">Model</span>
<span class="n">Using</span> <span class="n">TensorFlow</span> <span class="n">backend</span><span class="o">.</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">2</span><span class="p">]:</span> <span class="kn">from</span> <span class="nn">twgeo.data</span> <span class="k">import</span> <span class="n">twus_dataset</span> <span class="k">as</span> <span class="n">twus</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">3</span><span class="p">]:</span> <span class="n">x_train</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">x_dev</span><span class="p">,</span> <span class="n">y_dev</span><span class="p">,</span> <span class="n">x_test</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">twus</span><span class="o">.</span><span class="n">load_state_data</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="s1">&#39;small&#39;</span><span class="p">)</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">4</span><span class="p">]:</span> <span class="n">geoModel</span> <span class="o">=</span> <span class="n">Model</span><span class="p">()</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">5</span><span class="p">]:</span> <span class="n">geoModel</span><span class="o">.</span><span class="n">load_saved_model</span><span class="p">(</span><span class="s1">&#39;mymodel&#39;</span><span class="p">)</span>
<span class="n">Loading</span> <span class="n">saved</span> <span class="n">model</span><span class="o">...</span>

<span class="n">In</span> <span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="n">geoModel</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x_test</span><span class="p">)</span>
<span class="n">Out</span><span class="p">[</span><span class="mi">6</span><span class="p">]:</span> <span class="n">array</span><span class="p">([</span><span class="s1">&#39;CA&#39;</span><span class="p">,</span> <span class="s1">&#39;FL&#39;</span><span class="p">,</span> <span class="s1">&#39;NY&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="s1">&#39;TX&#39;</span><span class="p">,</span> <span class="s1">&#39;MA&#39;</span><span class="p">,</span> <span class="s1">&#39;KY&#39;</span><span class="p">],</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">object</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="results">
<h2>Results<a class="headerlink" href="#results" title="Permalink to this headline">¶</a></h2>
<p>The built-in TWUS dataset was used to train US State and US Census Region classifiers. Using a hidden layer size of
300 neurons, timestep window of 500 words and a vocabulary size of 50,000 words, the model achieves the following results.</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="28%" />
<col width="34%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Classification Task</th>
<th class="head">Test Set Accuracy</th>
<th class="head">Test Set Accuracy &#64; 5</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>US Census Region</td>
<td>73.95%</td>
<td>N/A</td>
</tr>
<tr class="row-odd"><td>US State</td>
<td>51.44%</td>
<td>75.39%</td>
</tr>
</tbody>
</table>
<div class="toctree-wrapper compound">
<p class="caption"><span class="caption-text">API</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="source/twgeo.data.html">Data</a></li>
<li class="toctree-l1"><a class="reference internal" href="source/twgeo.models.html">Models</a></li>
</ul>
</div>
</div>
</div>
<div class="section" id="indices-and-tables">
<h1>Indices and tables<a class="headerlink" href="#indices-and-tables" title="Permalink to this headline">¶</a></h1>
<ul class="simple">
<li><a class="reference internal" href="genindex.html"><span class="std std-ref">Index</span></a></li>
<li><a class="reference internal" href="py-modindex.html"><span class="std std-ref">Module Index</span></a></li>
</ul>
</div>


           </div>
           <div class="articleComments">
            
           </div>
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="source/twgeo.data.html" class="btn btn-neutral float-right" title="Data" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a>
      
      
    </div>
  

  <hr/>

  <div role="contentinfo">
    <p>
        &copy; Copyright 2017, Javier Matias.

    </p>
  </div>
  Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. 

</footer>

        </div>
      </div>

    </section>

  </div>
  


  

    <script type="text/javascript">
        var DOCUMENTATION_OPTIONS = {
            URL_ROOT:'./',
            VERSION:'0.1',
            COLLAPSE_INDEX:false,
            FILE_SUFFIX:'.html',
            HAS_SOURCE:  true,
            SOURCELINK_SUFFIX: '.txt'
        };
    </script>
      <script type="text/javascript" src="_static/jquery.js"></script>
      <script type="text/javascript" src="_static/underscore.js"></script>
      <script type="text/javascript" src="_static/doctools.js"></script>
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

  

  
  
    <script type="text/javascript" src="_static/js/theme.js"></script>
  

  
  
  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.StickyNav.enable();
      });
  </script>
   

</body>
</html>